package net.oschina.snmputil.iputils;

import java.math.BigDecimal;

/**
 * 
 * @author zdc
 *
 */
public class ConversionUtils {
	/***
	 * 
	 * 将二进制字符串转化为10进制
	 * @param hex
	 * @return
	 */
	public static int hexStringToAlgorism(String hex) {
		hex = hex.toUpperCase();
		int max = hex.length();
		int result = 0;
		for (int i = max; i > 0; i--) {
			char c = hex.charAt(i - 1);
			int algorism = 0;
			if (c >= '0' && c <= '9') {
				algorism = c - '0';
			} else {
				algorism = c - 55;
			}
			result += Math.pow(16, max - i) * algorism;
		}
		return result;
	}
	/**
	 * 处理差值32位寄存器使用
	 * 
	 * @param before
	 * @param now
	 * @return
	 */
	public static Long getDifference32(Long before, Long now) {
		Long tmp = now - before;
		if (tmp >= 0) {
			return tmp;

		} else {
			return 4294967296L - before + now;
		}
	}

	/**
	 * 处理差值16位寄存器使用
	 * 
	 * @param before
	 * @param now
	 * @return
	 */
	public static Long getDifference16(Long before, Long now) {
		Long tmp = now - before;
		if (tmp >= 0) {
			return tmp;

		} else {
			return 65536L - before + now;
		}
	}

	/**
	 * 处理差值32位寄存器使用
	 * 
	 * @param before
	 * @param now
	 * @return
	 */
	public static BigDecimal getDifference32(BigDecimal before, BigDecimal now) {

		if (before.compareTo(new BigDecimal("4294967296")) == 1
				|| now.compareTo(new BigDecimal("4294967296")) == -1) {
			BigDecimal tmp = now.subtract(before);
			BigDecimal bigDecimal = new BigDecimal("0");
			if (tmp.compareTo(bigDecimal) == 1
					|| tmp.compareTo(bigDecimal) == 0) {
				return tmp;
			} else {
				return new BigDecimal("4294967296").subtract(before).add(now);
			}
		} else {

			return getDifference64(before, now);
		}
		// BigDecimal bigDecimal
		// Long tmp = now - before;
		// if (tmp >= 0) {
		// return tmp;
		// } else {
		// return 4294967296L - before + now;
		// }
	}
/**
 64位差值计算
*/
	public static BigDecimal getDifference64(BigDecimal before, BigDecimal now) {
		BigDecimal tmp = now.subtract(before);
		BigDecimal bigDecimal = new BigDecimal("0");
		if (tmp.compareTo(bigDecimal) == 1 || tmp.compareTo(bigDecimal) == 0) {
			return tmp;
		} else {
			return new BigDecimal("18446744073709551616").subtract(before).add(
					now);
		}

	}

}
